package com.hspedu.ticket;

/**
 * @author LiuJinTao
 * @className SellTicket
 * @date 2024/06/23 15:54
 * @description 使用多线程模拟三个窗口同时售票 100 张
 */
public class SellTicket {
    public static void main(String[] args) {
        // 测试
//        SellTicket01 sellTicket01 = new SellTicket01();
//        SellTicket01 sellTicket02 = new SellTicket01();
//        SellTicket01 sellTicket03 = new SellTicket01();
//
//        // 出现票数超卖
//        sellTicket01.start();
//        sellTicket02.start();
//        sellTicket03.start();

        SellTicket02 sellTicket02 = new SellTicket02();
        Thread thread1 = new Thread(sellTicket02);
        Thread thread2 = new Thread(sellTicket02);
        Thread thread3 = new Thread(sellTicket02);
        thread1.start();
        thread2.start();
        thread3.start();

    }
}

// 使用 thread 方式
class SellTicket01 extends Thread {
    private static int ticketNum = 100;// 让多个线程共享

    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束..");
                break;
            }

            // 休眠 50 毫秒
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("窗口：" + Thread.currentThread().getName() + "  售出一张票。剩余票数："
                                + (--ticketNum));
        }
    }
}

// 使用 Runnable 方式
class SellTicket02 implements Runnable {
    private int ticketNum = 100;// 让多个线程共享

    @Override
    public void run() {
        while (true) {
            if (ticketNum <= 0) {
                System.out.println("售票结束..");
                break;
            }

            // 休眠 50 毫秒
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            System.out.println("窗口：" + Thread.currentThread().getName() + "  售出一张票。剩余票数："
                    + (--ticketNum));
        }
    }
}